from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from sqlalchemy import select, func
from typing import List, Optional
import re
import random
from ..db import get_db
from ..models import Knowledge, User, ReviewTask, UserAnswer, KnowledgeFolderLink
from ..security import get_current_user
from pydantic import BaseModel
from datetime import datetime

router = APIRouter()

class QuestionItem(BaseModel):
    knowledge_id: int
    card_id: str
    question: str
    answer_html: str
    title: str
    in_plan: bool = False

class AnswerCreate(BaseModel):
    knowledge_id: int
    card_id: str
    content: str

class AnswerHistoryItem(BaseModel):
    id: int
    content: str
    created_at: datetime

@router.get("/questions", response_model=List[QuestionItem])
def get_questions(
    folder_id: Optional[int] = None,
    in_plan: Optional[bool] = None, # None=All, True=In Plan, False=Not In Plan
    order: str = Query("seq", enum=["seq", "random"]),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    # 1. Fetch Knowledge items
    q = db.query(Knowledge).filter(Knowledge.owner_id == current_user.id, Knowledge.is_deleted == False)
    
    if folder_id is not None:
        q = q.join(KnowledgeFolderLink, KnowledgeFolderLink.knowledge_id == Knowledge.id).filter(KnowledgeFolderLink.folder_id == folder_id)
    
    knowledge_items = q.all()
    if not knowledge_items:
        return []

    # 2. Fetch ReviewTasks for these items to optimize checking
    k_ids = [k.id for k in knowledge_items]
    review_tasks = db.query(ReviewTask).filter(
        ReviewTask.owner_id == current_user.id,
        ReviewTask.knowledge_id.in_(k_ids)
    ).all()
    
    # Set of (knowledge_id, card_id) that are in plan
    plan_set = set((rt.knowledge_id, rt.card_id) for rt in review_tasks)

    questions = []
    
    # 3. Parse and Filter
    # Regex to match section.qa
    # <section class="qa" data-id="card-123"> ... </section>
    # We need to capture data-id, h3 content (question), and the rest (answer)
    # Note: The answer might contain newlines, so use DOTALL.
    # The answer is everything after </h3> until </section>
    
    pattern = re.compile(r'<section class="qa" data-id="([^"]+)">\s*<h3>(.*?)</h3>(.*?)<\/section>', re.DOTALL)

    for k in knowledge_items:
        if not k.body:
            continue
            
        matches = pattern.findall(k.body)
        for card_id, question, answer_html in matches:
            is_in_plan = (k.id, card_id) in plan_set
            
            # Filter logic
            if in_plan is True and not is_in_plan:
                continue
            if in_plan is False and is_in_plan:
                continue
                
            questions.append(QuestionItem(
                knowledge_id=k.id,
                card_id=card_id,
                question=question.strip(),
                answer_html=answer_html.strip(),
                title=k.title,
                in_plan=is_in_plan
            ))

    # 4. Order
    if order == "random":
        random.shuffle(questions)
    
    return questions

@router.post("/answers")
def submit_answer(
    answer: AnswerCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    # Verify knowledge exists and belongs to user (optional but good practice)
    # For speed, just assume valid if knowledge_id is passed from our own API.
    # But let's check ownership to be safe.
    # Actually, just insert.
    
    new_answer = UserAnswer(
        user_id=current_user.id,
        knowledge_id=answer.knowledge_id,
        card_id=answer.card_id,
        content=answer.content
    )
    db.add(new_answer)
    db.commit()
    return {"ok": True}

@router.get("/answers/{knowledge_id}/{card_id}", response_model=List[AnswerHistoryItem])
def get_answer_history(
    knowledge_id: int,
    card_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    answers = db.query(UserAnswer).filter(
        UserAnswer.user_id == current_user.id,
        UserAnswer.knowledge_id == knowledge_id,
        UserAnswer.card_id == card_id
    ).order_by(UserAnswer.created_at.desc()).all()
    
    return answers
